<template>
  <el-container>
    <aside-layout></aside-layout>
    <el-main>
      <el-row :gutter="20">
        <!-- 统计信息模块 -->
        <el-col :span="8">
          <el-card shadow="hover" class="statistics-card" style="border-radius: 10px;">
            <div slot="header" class="clearfix">
              <span style="font-weight: bold; font-size: 18px;">统计信息</span>
            </div>
            <div class="statistics">
              <div class="stat-item">
                <i class="el-icon-user-solid stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">总护工人数</p>
                  <p class="stat-value" style="color: #409EFF;">{{ nurseList.length }}</p>
                </div>
              </div>
              <div class="stat-item">
                <i class="el-icon-s-check stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">在岗人数</p>
                  <p class="stat-value" style="color: #67C23A;">{{ onDutyCount }}</p>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 护工技能分布图 -->
        <el-col :span="16">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>护工技能分布</span>
            </div>
            <div ref="skillsChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 最近活动日志 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>最近活动日志</span>
              <el-button type="primary" icon="el-icon-plus" @click="handleAddActivity" style="float: right; margin-top: 10px;">新增日志</el-button>
            </div>
            <ul class="activity-log">
              <li v-for="(log, index) in recentActivities" :key="index">
                {{ log.activity }}
                <el-button type="text" @click="handleEditActivity(log)">编辑</el-button>
                <el-button type="text" @click="handleDeleteActivity(log)" class="delete-btn">删除</el-button>
              </li>
            </ul>
          </el-card>
        </el-col>

        <!-- 待办事项 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>待办事项</span>
              <el-button type="primary" icon="el-icon-plus" @click="handleAddTodo" style="float: right;">新增事项</el-button>
            </div>
            <ul class="todo-list">
              <li v-for="(task, index) in todoList" :key="index">
                <el-checkbox v-model="task.completed">{{ task.text }}</el-checkbox>
                <el-button type="text" @click="handleEditTodo(task)">编辑</el-button>
                <el-button type="text" @click="handleDeleteTodo(task)" class="delete-btn">删除</el-button>
              </li>
            </ul>
          </el-card>
        </el-col>
      </el-row>

      <!-- 护工管理表格 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>护工管理</span>
              <el-button type="primary" icon="el-icon-plus" @click="handleAdd" style="float: right;">新增护工</el-button>
            </div>
            <div class="operation-bar">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索姓名"
                prefix-icon="el-icon-search"
                style="width: 200px; margin-right: 20px;"
                @keyup.enter.native="handleSearch"
              ></el-input>
            </div>
            <el-table :data="filteredNurseList" style="width: 100%" border>
              <el-table-column prop="name" label="姓名" width="120"></el-table-column>
              <el-table-column prop="age" label="年龄" width="80"></el-table-column>
              <el-table-column prop="phone" label="联系电话" width="150"></el-table-column>
              <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
              <el-table-column prop="address" label="地址" width="250"></el-table-column>
              <el-table-column prop="emergencyContact" label="紧急联系人" width="150"></el-table-column>
              <el-table-column prop="skills" label="技能" width="150"></el-table-column>
              <el-table-column prop="experience" label="工作经验" width="120"></el-table-column>
              <el-table-column prop="rating" label="评价" width="100">
                <template slot-scope="scope">
                  <el-rate v-model="scope.row.rating" disabled></el-rate>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.status === '在岗' ? 'success' : 'info'">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="text" @click="handleDelete(scope.row)" class="delete-btn">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <!-- 新增/编辑护工对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
        <el-form :model="form" label-width="120px">
          <el-form-item label="姓名">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="form.age"></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="form.address"></el-input>
          </el-form-item>
          <el-form-item label="紧急联系人">
            <el-input v-model="form.emergencyContact"></el-input>
          </el-form-item>
          <el-form-item label="技能">
            <el-input v-model="form.skills"></el-input>
          </el-form-item>
          <el-form-item label="工作经验">
            <el-input v-model="form.experience"></el-input>
          </el-form-item>
          <el-form-item label="评价">
            <el-rate v-model="form.rating"></el-rate>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="form.status" placeholder="选择状态">
              <el-option label="在岗" value="在岗"></el-option>
              <el-option label="休假" value="休假"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增/编辑日志对话框 -->
      <el-dialog :title="activityDialogTitle" :visible.sync="activityDialogVisible">
        <el-form :model="activityForm" label-width="120px">
          <el-form-item label="日志内容">
            <el-input v-model="activityForm.activity"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="activityDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleActivitySubmit">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增/编辑待办事项对话框 -->
      <el-dialog :title="todoDialogTitle" :visible.sync="todoDialogVisible">
        <el-form :model="todoForm" label-width="120px">
          <el-form-item label="事项内容">
            <el-input v-model="todoForm.text"></el-input>
          </el-form-item>
          <el-form-item label="是否完成">
            <el-checkbox v-model="todoForm.completed"></el-checkbox>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="todoDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleTodoSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import AsideLayout from '@/layout/asideLayout.vue'
import * as echarts from 'echarts'
import axios from 'axios'

export default {
  components: {
    AsideLayout
  },
  name: 'NurseManagement',
  data() {
    return {
      searchKeyword: '',
      nurseList: [],
      recentActivities: [],
      todoList: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        name: '',
        age: '',
        phone: '',
        email: '',
        address: '',
        emergencyContact: '',
        skills: '',
        experience: '',
        rating: 0,
        status: ''
      },
      activityDialogVisible: false,
      activityDialogTitle: '',
      activityForm: {
        id: null,
        activity: ''
      },
      todoDialogVisible: false,
      todoDialogTitle: '',
      todoForm: {
        id: null,
        text: '',
        completed: false
      },
      skillsChartOptions: {
        title: {
          text: '护工技能分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: 'bottom'
        },
        series: [
          {
            name: '技能',
            type: 'pie',
            radius: '50%',
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    }
  },
  computed: {
    filteredNurseList() {
      return this.nurseList.filter(nurse => {
        return this.searchKeyword === '' || nurse.name.includes(this.searchKeyword)
      })
    },
    onDutyCount() {
      return this.nurseList.filter(nurse => nurse.status === '在岗').length
    }
  },
  mounted() {
    this.fetchNurseList()
      .then(() => {
        this.initCharts()
      })
    this.fetchRecentActivities()
    this.fetchTodoList()
  },
  methods: {
    async fetchNurseList() {
      try {
        const response = await axios.get('http://localhost:3000/api/nurses');
        this.nurseList = response.data;
        console.log('Nurse List:', this.nurseList);
        this.updateSkillsChartData();
      } catch (error) {
        console.error('Error fetching nurse list:', error);
      }
    },
    fetchRecentActivities() {
      axios.get('http://localhost:3000/api/recent-activities')
        .then(response => {
          this.recentActivities = response.data
        })
        .catch(error => {
          console.error('Error fetching recent activities:', error)
        })
    },
    fetchTodoList() {
      axios.get('http://localhost:3000/api/todo-list')
        .then(response => {
          this.todoList = response.data
        })
        .catch(error => {
          console.error('Error fetching todo list:', error)
        })
    },
    initCharts() {
      const chartContainer = this.$refs.skillsChart
      const chartInstance = echarts.init(chartContainer)
      this.updateSkillsChartData()
      chartInstance.setOption(this.skillsChartOptions)
    },
    updateSkillsChartData() {
      const skillCounts = this.nurseList.reduce((acc, nurse) => {
        if (nurse.skills) {
          const skills = nurse.skills.split(',');
          skills.forEach(skill => {
            skill = skill.trim();
            acc[skill] = (acc[skill] || 0) + 1;
          });
        }
        return acc;
      }, {});

      console.log('Skill Counts:', skillCounts);

      const totalNurses = this.nurseList.length;
      this.skillsChartOptions.series[0].data = Object.entries(skillCounts).map(([key, value]) => ({
        name: key,
        value: totalNurses ? (value / totalNurses) * 100 : 0
      }));

      console.log('Chart Data:', this.skillsChartOptions.series[0].data);

      const chartContainer = this.$refs.skillsChart
      const chartInstance = echarts.init(chartContainer)
      chartInstance.setOption(this.skillsChartOptions)
    },
    handleAdd() {
      this.dialogTitle = '新增护工'
      this.form = {
        id: null,
        name: '',
        age: '',
        phone: '',
        email: '',
        address: '',
        emergencyContact: '',
        skills: '',
        experience: '',
        rating: 0,
        status: ''
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑护工'
      this.form = { ...row }
      this.dialogVisible = true
    },
    handleSubmit() {
      if (this.form.id) {
        axios.put(`http://localhost:3000/api/nurses/${this.form.id}`, this.form)
          .then(() => {
            this.fetchNurseList()
            this.dialogVisible = false
            this.$message.success('更新护工信息成功')
          })
          .catch(error => {
            console.error('Error updating nurse:', error)
            this.$message.error('更新护工信息失败')
          })
      } else {
        axios.post('http://localhost:3000/api/nurses', this.form)
          .then(() => {
            this.fetchNurseList()
            this.dialogVisible = false
            this.$message.success('新增护工成功')
          })
          .catch(error => {
            console.error('Error adding nurse:', error)
            this.$message.error('新增护工失败')
          })
      }
    },
    handleDelete(row) {
      this.$confirm(`确认删除护工 ${row.name} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/nurses/${row.id}`)
          .then(() => {
            this.fetchNurseList()
            this.$message.success('删除成功')
          })
          .catch(error => {
            console.error('Error deleting nurse:', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleAddActivity() {
      this.activityDialogTitle = '新增日志'
      this.activityForm = {
        id: null,
        activity: ''
      }
      this.activityDialogVisible = true
    },
    handleEditActivity(log) {
      this.activityDialogTitle = '编辑日志'
      this.activityForm = { ...log }
      this.activityDialogVisible = true
    },
    handleActivitySubmit() {
      if (this.activityForm.id) {
        axios.put(`http://localhost:3000/api/recent-activities/${this.activityForm.id}`, this.activityForm)
          .then(() => {
            this.fetchRecentActivities()
            this.activityDialogVisible = false
            this.$message.success('更新日志成功')
          })
          .catch(error => {
            console.error('Error updating activity:', error)
            this.$message.error('更新日志失败')
          })
      } else {
        axios.post('http://localhost:3000/api/recent-activities', this.activityForm)
          .then(() => {
            this.fetchRecentActivities()
            this.activityDialogVisible = false
            this.$message.success('新增日志成功')
          })
          .catch(error => {
            console.error('Error adding activity:', error)
            this.$message.error('新增日志失败')
          })
      }
    },
    handleDeleteActivity(log) {
      this.$confirm(`确认删除日志 ${log.activity} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/recent-activities/${log.id}`)
          .then(() => {
            this.fetchRecentActivities()
            this.$message.success('删除成功')
          })
          .catch(error => {
            console.error('Error deleting activity:', error.response ? error.response.data : error);
            this.$message.error('删除失败');
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleAddTodo() {
      this.todoDialogTitle = '新增事项'
      this.todoForm = {
        id: null,
        text: '',
        completed: false
      }
      this.todoDialogVisible = true
    },
    handleEditTodo(task) {
      this.todoDialogTitle = '编辑事项'
      this.todoForm = { ...task }
      this.todoDialogVisible = true
    },
    handleTodoSubmit() {
      if (this.todoForm.id) {
        axios.put(`http://localhost:3000/api/todo-list/${this.todoForm.id}`, this.todoForm)
          .then(() => {
            this.fetchTodoList()
            this.todoDialogVisible = false
            this.$message.success('更新事项成功')
          })
          .catch(error => {
            console.error('Error updating todo:', error)
            this.$message.error('更新事项失败')
          })
      } else {
        axios.post('http://localhost:3000/api/todo-list', this.todoForm)
          .then(() => {
            this.fetchTodoList()
            this.todoDialogVisible = false
            this.$message.success('新增事项成功')
          })
          .catch(error => {
            console.error('Error adding todo:', error)
            this.$message.error('新增事项失败')
          })
      }
    },
    handleDeleteTodo(task) {
      this.$confirm(`确认删除事项 ${task.text} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/todo-list/${task.id}`)
          .then(() => {
            this.fetchTodoList()
            this.$message.success('删除成功')
          })
          .catch(error => {
            console.error('Error deleting todo:', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  },
  watch: {
    nurseList: {
      handler() {
        this.updateSkillsChartData();
      },
      deep: true
    }
  }
}
</script>

<style scoped>
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}

.el-container {
  height: 100vh; /* 使容器高度适应视口 */
}

.el-main {
  padding: 20px;
  overflow: auto; /* 允许内容溢出时滚动 */
}

.el-card {
  transition: transform 0.3s;
}

.el-card:hover {
  transform: translateY(-5px);
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

.statistics {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 5px;
}

.stat-icon {
  font-size: 24px;
  color: #409EFF;
  margin-right: 10px;
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.activity-log, .todo-list {
  list-style: none;
  padding: 0;
}

.activity-log li, .todo-list li {
  padding: 5px 0;
  border-bottom: 1px solid #ebeef5;
}

.todo-list li {
  display: flex;
  align-items: center;
}
</style>